from etcd_config_manager import EtcdConfigManager
from typing import Any, Dict
import time

class CachedEtcdConfigManager(EtcdConfigManager):
    def __init__(self, host: str = 'localhost', port: int = 2379, ttl: int = 30):
        super().__init__(host, port)
        self.cache = {}
        self.cache_ttl = ttl
        self.last_refresh = {}
    
    def get_config(self, key: str, default: Any = None, force_refresh: bool = False) -> Optional[Any]:
        """获取配置（带缓存）"""
        now = time.time()
        
        if (force_refresh or 
            key not in self.cache or 
            key not in self.last_refresh or
            now - self.last_refresh[key] > self.cache_ttl):
            
            value = super().get_config(key, default)
            self.cache[key] = value
            self.last_refresh[key] = now
            return value
        
        return self.cache[key]
    
    def put_config(self, key: str, value: Any) -> bool:
        """存储配置并清除缓存"""
        success = super().put_config(key, value)
        if success and key in self.cache:
            del self.cache[key]
            if key in self.last_refresh:
                del self.last_refresh[key]
        return success